var util = require('../../../../utils/util.js');
var api = require('../../../../config/api.js');

var app = getApp();

Page({
  data: {
    tmCrReqEntity: {},
    tmCrReqChdVos: [],
    reNum: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    let dataDetails = options.dataString;
    let tmCrReqEntity = JSON.parse(decodeURIComponent(dataDetails));
    // 前一页面传递试剂申领单主表实体
    this.setData({
      tmCrReqEntity: tmCrReqEntity
    });

    // 获取试剂申领，试剂详情信息
    util.request(api.MyReagentDetail, {reqId: tmCrReqEntity.reqId })
      .then(res => {
        if (res.code === 0) {
          this.setData({
            tmCrReqChdVos: res.tmCrReqChdVos
          });
        }
      });
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  // 归还剂量结束输入
  applyNumChange: function(e){
    // 获取选中下标位置
    let itemIndex = e.target.dataset.itemIndex;
    let tmCrReqChdVos = this.data.tmCrReqChdVos;

    // 归还剂量不能大于申请剂量
    if (parseInt(e.detail.value) > parseInt(tmCrReqChdVos[itemIndex].num)) {
      util.showErrorToast('不能大于申请');
      this.setData({
        reNum: ''
      });
      return false;
    }
    // 赋值
    tmCrReqChdVos[itemIndex].reagentNum = e.detail.value;

    this.setData({
      tmCrReqChdVos: tmCrReqChdVos
    });
  },
  // 提交申请
  commitApply: function () {
    // 获取选择试剂信息和对应数量、是否归还
    var tempReqs = this.data.tmCrReqChdVos.map(function (v) {
      return {chdId: v.chdId, reNum: v.reagentNum, difId: v.difId};
    });
    // 转换json格式传输
    let jsonText = JSON.stringify(tempReqs);
    // 申领单ID
    let reqId = this.data.tmCrReqEntity.reqId;

    util.request(api.ReagentRevert, {
      tmCrReqChdJson: jsonText,
      reqId: reqId
    }).then(function (res) {
      if (res.code === 0) {
        wx.redirectTo({
          url: '/pages/cr/businessHand/reagentRevert/reagentRevert'
        });
      } else {
        util.showErrorToast('提交失败');
      }
    }).catch(res => {
      util.showErrorToast('提交失败');
    });
  }
})